﻿using System;
using System.Diagnostics;
using System.Web;
using Glimpse.Core.Extensions;
using Glimpse.Core.Framework;
using System.Collections.Generic;
using System.Linq;
using Glimpse.Core.SerializationConverter;
using GlimpseWcf.Core;
using Newtonsoft.Json;
using System.ServiceModel.Dispatcher;
using Formatting = Newtonsoft.Json.Formatting;

namespace GlimpseWcf.Server
{
    public class WcfDispatchMessageInspector : IDispatchMessageInspector
    {
        private IGlimpseRuntime _runtime;
        private IFrameworkProvider _framework;
        private readonly Stopwatch _stopwatch = new Stopwatch();

        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            var cookies = CookieMessageHeader.ReadHeader(request).GetDictionary();
            foreach (var cookie in cookies)
                OperationContextWrapper.Current.Cookies.Add(new HttpCookie(cookie.Key, cookie.Value));

            var locator = new WcfServiceLocator();
            _framework = locator.GetInstance<IFrameworkProvider>();
            var factory = new Factory(locator);
            locator.Logger = factory.InstantiateLogger();
            _runtime = factory.InstantiateRuntime();
            _runtime.Initialize();
            _runtime.BeginRequest();
            _stopwatch.Start();

            return null;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            _stopwatch.Stop();
            _runtime.EndRequest();
            var tabResults = _framework.HttpRequestStore.Get<IDictionary<string, TabResult>>("__GlimpseTabResults");
            if (tabResults != null && tabResults.Count > 0)
            {
                var tabResultsDtoList = tabResults.Where(tR => tR.Value.Data != null).Select(tabResult => new TabResultDto { Name = tabResult.Value.Name, Data = JsonConvert.SerializeObject(tabResult.Value.Data,new JsonSerializerSettings{ NullValueHandling = NullValueHandling.Include, TypeNameHandling = TypeNameHandling.All}), ObjectType = tabResult.Value.Data.GetType().AssemblyQualifiedName }).ToList();
                reply.Headers.Add(new WcfGlimpseResponseMessageHeader(new WcfGlimpseResponse { TabResults = tabResultsDtoList }));
            }

        }
    }
}
